package com.mingserve.raw.listener;

import com.mingserve.common.core.constant.CacheConstants;
import com.mingserve.common.core.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis Key失效事件监听
 *
 * @author lvwshuai
 * @date 2023-04-07
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener
{
    private static final Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
//    @Autowired
//    private RedisService redisService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer)
    {
        super(listenerContainer);
    }
    private final RawListener rawListener = SpringUtils.getBean(RawListener.class);

    @Override
    public void onMessage(Message message, byte[] pattern)
    {
        String expiredKey = message.toString();
        // 判断工作机组过期失效key
        if (expiredKey.contains(CacheConstants.RAW_POINT_GROUP_EXPIRE_KEY)) {
            log.info("Point group expiredKey lost {}", expiredKey);
            // Redis 的过期键机制采用的是惰性删除和定期删除策略，导致在某些情况下，键过期后并不会立即被删除。redisTemplate.hasKey(key) 可能返回 true，即使该键已经过期
//            redisService.deleteObject(expiredKey);
            String[] str = expiredKey.replace(CacheConstants.RAW_POINT_GROUP_EXPIRE_KEY, "").split("-");
            rawListener.checkRawGroup(str[0]);
        }
    }
}
